
from django.contrib.auth import get_user_model
from rest_framework import serializers
from apps.vadmin.assets.models.check_records import CheckRecords 
from apps.vadmin.assets.models.assets_records import AssetRecords
from apps.vadmin.assets.models.accessories import Accessories
from apps.vadmin.assets.models.assets import Assets
from apps.vadmin.assets.models.components import Components
from apps.vadmin.assets.models.components_assets import Components_Assets 
from apps.vadmin.assets.models.accessories_users import Accessories_Users
from apps.vadmin.assets.models.consumables_users import Consumables_Users
from apps.vadmin.assets.models.license_seats import License_Seats
from apps.vadmin.assets.models.consumables import Consumables
from apps.vadmin.assets.models.consumables_records import ConsumableRecords
from apps.vadmin.assets.models.depreciations import Depreciations
from apps.vadmin.assets.models.kits import Kits
from apps.vadmin.assets.models.kits_accessories import KitsAccessories
from apps.vadmin.assets.models.kits_consumables import KitsConsumables
from apps.vadmin.assets.models.kits_licenses import KitsLicenses
from apps.vadmin.assets.models.kits_models import KitsModels
from apps.vadmin.assets.models.licenses import Licenses
from apps.vadmin.assets.models.maintenances import Maintenances
from apps.vadmin.assets.models.report import AssetStatusReport, CategoryTotalReport, UserCheckoutReport
from apps.vadmin.assets.models.uploads import Uploads
from apps.vadmin.assets.models.locations import Locations
from apps.vadmin.permission.serializers import UserProfileSerializer
from apps.vadmin.op_drf.serializers import CustomModelSerializer
from apps.vadmin.assets.models.suppliers import Suppliers
from apps.vadmin.assets.models.manufacturers import Manufacturers 
from apps.vadmin.assets.models.categories import Categories
from apps.vadmin.assets.models.models import Models 
from apps.vadmin.assets.models.report import AssetNowCheckoutReport

UserProfile = get_user_model()

class CategoriesSerializer(CustomModelSerializer):
    """
    简单分类序列化器
    """
    class Meta:
        model = Categories
        exclude = ('description', 'creator', 'modifier')

class ExportCategoriesSerializer(CustomModelSerializer):
    class Meta:
        model = Categories
        fields = ('id', 'name','create_datetime', 'category_type')

class CategoriesCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Categories
        fields = '__all__'

class ModelsSerializer(CustomModelSerializer):
    """
    型号序列化器
    """
    class Meta:
        model = Models 
        fields = '__all__'
        #exclude = ('description', 'creator', 'modifier')

    def get_fields(self):
        fields = super().get_fields()
        fields['category_name'] = serializers.CharField(source='category.name', read_only=True)
        fields['manufacturer_name'] = serializers.CharField(source='manufacturer.name', read_only=True)
        fields['depreciation_name'] = serializers.CharField(source='depreciation.name', read_only=True)
        return fields 

class ExportModelsSerializer(CustomModelSerializer):
    class Meta:
        model = Models 
        fields = ('id', 'name','create_datetime', 'model_number', 'eol',
                'requestable', 'notes','category_id','manufacturer_id')

class ModelsCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Models
        fields = '__all__'

class SuppliersSerializer(CustomModelSerializer):
    """
    供应商序列化器
    """
    class Meta:
        model = Suppliers 
        fields = ('id', 'name','create_datetime', 'state', 'city',
                'address','address2', 'contact','phone', 'email',
                'fax','url','zip','notes')

class ExportSuppliersSerializer(CustomModelSerializer):
    """
    供应商序列化器
    """
    class Meta:
        model = Suppliers 
        fields = '__all__'

class ManufacturersSerializer(CustomModelSerializer):
    """
    制造商序列化器
    """
    class Meta:
        model = Manufacturers 
        fields = '__all__'
        #exclude = ('description', 'creator', 'modifier')

class ExportManufacturersSerializer(CustomModelSerializer):
    """
    制造商序列化器
    """
    class Meta:
        model = Manufacturers 
        fields = ('id', 'name','create_datetime', 'url', 'support_url','support_phone','support_email')

class DepreciationsSerializer(CustomModelSerializer):
    """
    折旧序列化器
    """
    class Meta:
        model = Depreciations 
        fields = '__all__'

class ExportDepreciationsSerializer(CustomModelSerializer):
    class Meta:
        model = Depreciations 
        fields = ('id', 'name','create_datetime', 'months', 'depreciation_min')

class AssetsSerializer(CustomModelSerializer):
    """
    资产序列化器               
    """
    deleted_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    last_checkout = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    
    class Meta:
        model = Assets
        fields = '__all__'
        
    def get_fields(self):
        fields = super().get_fields()
        fields['model_name'] = serializers.CharField(source='model.name', read_only=True)
        fields['supplier_name'] = serializers.CharField(source='supplier.name', read_only=True)
        fields['location_name'] = serializers.CharField(source='location.name', read_only=True)
        return fields 

class ImportAssetsSerializer(CustomModelSerializer):
    class Meta:
        model = Assets
        fields = ('id', 'name', 'asset_tag', 'serial', 'purchase_date', 'asset_eol_date', 
                'purchase_cost', 'order_number','notes','physical','warranty_months','depreciate',
                'requestable','last_checkout','expected_checkin','assigned_type','last_audit_date', 'next_audit_date','checkin_counter',
                'checkout_counter','requests_counter','byod','model_id','status','supplier_id','assigned_to_id','assigned_to_name','location_id')

class ExportAssetsSerializer(CustomModelSerializer):
    class Meta:
        model = Assets
        fields = ('id', 'name', 'asset_tag', 'serial', 'purchase_date', 'asset_eol_date', 
                'purchase_cost', 'order_number','notes','physical','warranty_months','depreciate',
                'requestable','last_checkout','expected_checkin','assigned_type','last_audit_date', 'next_audit_date','checkin_counter',
                'checkout_counter','requests_counter','byod','model_id','status','supplier_id','assigned_to_id','assigned_to_name','location_id')

class AssetsCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Assets
        fields = '__all__'



class AccessoriesSerializer(CustomModelSerializer):
    """
    附属品配件列化器
    """
    class Meta:
        model = Accessories
        fields = '__all__'

    def get_fields(self):
        fields = super().get_fields()
        fields['category_name'] = serializers.CharField(source='category.name', read_only=True)
        fields['manufacturer_name'] = serializers.CharField(source='manufacturer.name', read_only=True)
        fields['supplier_name'] = serializers.CharField(source='supplier.name', read_only=True)
        fields['location_name'] = serializers.CharField(source='location.name', read_only=True)
        return fields 

class ExportAccessoriesSerializer(CustomModelSerializer):
    class Meta:
        model = Accessories
        fields = ('id', 'name', 'create_datetime', 'qty', 'requestable', 'purchase_date',
                'purchase_cost','order_number','min_amt','model_number','notes','category_id',
                'manufacturer_id','supplier_id','checkout_qty','location_id') 

class AccessoriesCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Accessories
        fields = '__all__'

class ComponentsSerializer(CustomModelSerializer):
    """
    资产组件列化器
    """
    class Meta:
        model = Components
        fields = '__all__'

    def get_fields(self):
        fields = super().get_fields()
        fields['category_name'] = serializers.CharField(source='category.name', read_only=True)
        fields['manufacturer_name'] = serializers.CharField(source='manufacturer.name', read_only=True)
        fields['supplier_name'] = serializers.CharField(source='supplier.name', read_only=True)
        fields['location_name'] = serializers.CharField(source='location.name', read_only=True)
        return fields 

class ExportComponentsSerializer(CustomModelSerializer):
    class Meta:
        model = Components
        fields = ('id', 'name','serial','create_datetime', 'qty', 'purchase_date',
                'purchase_cost','order_number','min_amt','notes',
                'category_id', 'manufacturer_id','supplier_id','checkout_qty','location_id') 

class ComponentsCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Components
        fields = '__all__'

class ConsumablesSerializer(CustomModelSerializer):
    """
    消耗品列化器
    """
    class Meta:
        model = Consumables
        fields = '__all__'

    def get_fields(self):
        fields = super().get_fields()
        fields['category_name'] = serializers.CharField(source='category.name', read_only=True)
        fields['manufacturer_name'] = serializers.CharField(source='manufacturer.name', read_only=True)
        fields['supplier_name'] = serializers.CharField(source='supplier.name', read_only=True)
        fields['location_name'] = serializers.CharField(source='location.name', read_only=True)
        return fields 

class ExportConsumablesSerializer(CustomModelSerializer):
    class Meta:
        model = Consumables
        fields = ('id', 'name','item_no','create_datetime', 'qty', 'requestable','purchase_date',
                'purchase_cost','order_number','min_amt','model_number','notes',
                'category_id', 'manufacturer_id','supplier_id','checkout_qty','location_id') 

class ConsumablesCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Consumables
        fields = '__all__'
    
class LicensesSerializer(CustomModelSerializer):
    """
    软件许可列化器
    """
    class Meta:
        model = Licenses
        #exclude = ('description', 'creator', 'modifier')
        fields = '__all__'

    def get_fields(self):
        fields = super().get_fields()
        fields['category_name'] = serializers.CharField(source='category.name', read_only=True)
        fields['manufacturer_name'] = serializers.CharField(source='manufacturer.name', read_only=True)
        fields['supplier_name'] = serializers.CharField(source='supplier.name', read_only=True)
        fields['depreciation_name'] = serializers.CharField(source='depreciation.name', read_only=True)
        return fields 

class ExportLicensesSerializer(CustomModelSerializer):
    class Meta:
        model = Licenses
        fields = ('id', 'name','serial','create_datetime', 'seats', 'purchase_date',
                'purchase_cost','order_number','reassignable','license_name','license_email','notes',
                'expiration_date','termination_date', 'category_id', 'manufacturer_id','supplier_id','checkout_seats' ) 

class LicensesCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Licenses
        fields = '__all__'

class KitsSerializer(CustomModelSerializer):
    """
    资产套件列化器
    """
    class Meta:
        model = Kits
        exclude = ('description', 'creator', 'modifier')

class KitsCreateUpdateSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Kits
        fields = '__all__'

class KitsLicensesSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = KitsLicenses
        fields = '__all__'

    def get_fields(self):
        fields = super().get_fields()
        fields['license_name'] = serializers.CharField(source='license.name', read_only=True)
        return fields 


class KitsModelsSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = KitsModels
        fields = '__all__'

    def get_fields(self):
        fields = super().get_fields()
        fields['model_name'] = serializers.CharField(source='model.name', read_only=True)
        return fields 

class KitsAccessoriesSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = KitsAccessories
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['accessory_name'] = serializers.CharField(source='accessory.name', read_only=True)
        return fields 

class KitsConsumablesSerializer(CustomModelSerializer):
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = KitsConsumables
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['consumable_name'] = serializers.CharField(source='consumable.name', read_only=True)
        return fields 


class MaintenancesSerializer(CustomModelSerializer):
    """ 
    资产维护表
    """
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Maintenances
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['asset_tag'] = serializers.CharField(source='asset.tag', read_only=True)
        fields['asset_name'] = serializers.CharField(source='asset.name', read_only=True)
        fields['supplier_name'] = serializers.CharField(source='supplier.name', read_only=True)
        fields['location_name'] = serializers.CharField(source='asset.location.name', read_only=True)
        fields['model_name'] = serializers.CharField(source='asset.model.name', read_only=True)
        return fields 


class UploadsSerializer(CustomModelSerializer):
    """ 
    上传文件表
    """
    def save(self, **kwargs):
        return super().save(**kwargs)

    class Meta:
        model = Uploads
        fields = '__all__' 

class LocationsSerializer(CustomModelSerializer):
    """ 
    位置表序列器
    """
    def init_ancestors(self,validated_data):
        pid = validated_data.get('parent_id',None)
        p = Locations.objects.filter(id=pid).first()
        if p is not None:
            validated_data["ancestors"] = f"{p.ancestors},{p.id}"
        else:
            validated_data["ancestors"] = "0"
        return None
        

    def create(self, validated_data):
        self.init_ancestors(validated_data)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        self.init_ancestors(validated_data)
        return super().update(instance, validated_data)

    class Meta:
        model = Locations
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['manager_name'] = serializers.CharField(source='manager.name', read_only=True)
        return fields 

class ExportLocationsSerializer(CustomModelSerializer):
    class Meta:
        model = Locations
        fields = ('id', 'name','create_datetime', 'country', 'province',
                  'city','district','address','address2','zip',
                  'ancestors','currency','parent_id','manager_id')

class AssetRecordsSerializer(CustomModelSerializer):

    checkin_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S',required=False)
    
    """
    资产借用记录表
    """
    def save(self, **kwargs):
        return super().save(**kwargs)
    
    class Meta:
        model = AssetRecords
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['asset_name'] = serializers.CharField(source='asset.name', read_only=True)
        return fields 


    


class UserCheckoutReportSerializer(CustomModelSerializer):
    checkin_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S',required=False)
    """
    用户资产借用报表
    """
    class Meta:
        model = UserCheckoutReport 
        fields = '__all__' 

class AssetStatusReportSerializer(CustomModelSerializer):
    class Meta:
        model = AssetStatusReport
        fields = '__all__' 

class CategoryTotalReportSerializer(CustomModelSerializer):
    class Meta:
        model = CategoryTotalReport
        fields = '__all__' 


class CheckRecordsSerializer(CustomModelSerializer):
    check_datetime = serializers.DateTimeField(format='%Y-%m-%d',required=False)
    class Meta:
        model = CheckRecords
        fields = '__all__' 

class ComponentsAssetsSerializer(CustomModelSerializer):
    class Meta:
        model = Components_Assets
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['component_name'] = serializers.CharField(source='component.name', read_only=True)
        fields['purchase_cost'] = serializers.CharField(source='component.purchase_cost', read_only=True)
        fields['assigned_asset_name'] = serializers.CharField(source='asset.name', read_only=True)
        return fields 

class AccessoriesUsersSerializer(CustomModelSerializer):
    class Meta:
        model = Accessories_Users
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['assigned_to_name'] = serializers.CharField(source='assigned_to.name', read_only=True)
        fields['accessory_name'] = serializers.CharField(source='accessory.name', read_only=True)
        fields['purchase_cost'] = serializers.CharField(source='accessory.purchase_cost', read_only=True)
        return fields 

class ConsumablesUsersSerializer(CustomModelSerializer):
    class Meta:
        model = Consumables_Users
        fields = '__all__' 

    def get_fields(self):
        fields = super().get_fields()
        fields['assigned_to_name'] = serializers.CharField(source='assigned_to.name', read_only=True)
        fields['consumeable_name'] = serializers.CharField(source='consumable.name', read_only=True)
        fields['purchase_cost'] = serializers.CharField(source='consumable.purchase_cost', read_only=True)
        return fields 

class LicenseSeatsSerializer(CustomModelSerializer):
    class Meta:
        model = License_Seats 
        fields = '__all__' 
    def get_fields(self):
        fields = super().get_fields()
        fields['license_name'] = serializers.CharField(source='license.name', read_only=True)
        fields['purchase_cost'] = serializers.CharField(source='license.purchase_cost', read_only=True)
        fields['assigned_to_name'] = serializers.CharField(source='assigned_to.name', read_only=True)
        fields['assigned_asset_name'] = serializers.CharField(source='asset.name', read_only=True)
        return fields 

class AssetNowCheckoutReportSerializer(CustomModelSerializer):
    create_datetime = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S',required=False)
    class Meta:
        model = AssetNowCheckoutReport
        fields = '__all__' 
